<?php

class orquestacion extends ActiveRecord {
	public $srv1; //int
	public $srv2; //int

	// Parametros
	public $connections = array(); // array de conexiones
	
	public function __construct ($datos = null) {
		parent::__construct ($datos);
		$this->cargar_conexiones();
	}

    public function insert() {
        $sql = "INSERT INTO orquestacion
		               (id_service_1, id_service_2)
					   VALUES
					   ($this->srv1, $this->srv2)";
		
		$this->id = executeId($sql);

		foreach( $this->connections as $conn )
		{
			$conn->insert($this->id);
		}
	}
	
	public function update($datos = null) {
      /*  $this->__cargarParametros($datos);
        $sql = "UPDATE orquestacion
                SET id_service_1 = $this->srv1,
					id_service_2 = $this->srv2
                WHERE id = $this->id";
        return execute($sql);*/
    }
	

	public function delete() 
	{
		foreach( $this->connections as $conn )
		{
			$conn->delete();
		}
	
		return parent::delete();
	}
	
	public function delete_by_id($id) 
	{
		$sql = "DELETE FROM orquestacion WHERE id=$id";
		execute($sql);
		
		$sql = "DELETE FROM connections WHERE id_orq=$id";
		return execute($sql);
	}

    private function cargar_array_conexiones()
	{
		$sql = "SELECT * FROM connections
				WHERE id_orq = $this->id";
		return queryObjectList($sql, $this->getClass());
	}

    public function cargar_conexiones()
	{
		if (!$this->id) return;
		$this->connections = $this->cargar_array_conexiones();
	}
	
	private function grabar_connections() {
		foreach ($this->connections as $conn) {
			$conn->save();
		}
	}
	
	public function save() {
		parent::save();
		$this->grabar_connections();
	}
	
	public function find_All()
	{
		$sql = " SELECT o.id as id, s1.nombre as n1, s2.nombre as n2 FROM orquestacion o
				 INNER JOIN servicios s1 ON o.id_service_1 = s1.id
				 INNER JOIN servicios s2 ON o.id_service_2 = s2.id
 				 ORDER BY o.id;";
		return queryObjectList($sql, $this->getClass());
	}
	
	public function find($id)
	{
		$sql = "SELECT * FROM orquestacion WHERE id =$id";
		return queryObjectList($sql, $this->getClass());
	}
	
	public function find_service1($id)
	{
		$sql = "SELECT * FROM orquestacion WHERE id_service_1 =$id order by id";
		return queryObjectList($sql, $this->getClass());
	}
	
	public function find_service2($id)
	{
		$sql = "SELECT * FROM orquestacion WHERE id_service_2 =$id order by id";
		return queryObjectList($sql, $this->getClass());
	}
}

?>